<?php

class User
{
	private $SnapUserID = 0;
	private $LongName;
	private $ShortName;
	private $Password;
	private $Email;
	private $GroupID;
	
	
	public function __construct($SnapUserID)
	{
		if($SnapUserID<>0)
		{
			$database=$GLOBALS['DATABASE']->Recopy();
			$sql = "SELECT m.SnapUserID, m.SnapUserGroupID, u.SnapUserID, u.LongName, u.ShortName, u.Password, u.email ";
			$sql .= "FROM ";
			$sql .= "(SnapUserGroupMembers AS m ";
			$sql .= "INNER JOIN SnapUsers AS u ON m.SnapUserID = u.SnapUserID) ";
			$sql .= "WHERE m.SnapUserID = ".$SnapUserID;
			$database->executeSQL($sql);
			$row=$database->getRow();
			$this->SnapUserID = $SnapUserID;
			$this->LongName = $row['LongName'];
			$this->ShortName = $row['ShortName'];
			$this->Password = $row['Password'];
			$this->Email = $row['email'];
			$this->GroupID = $row['SnapUserGroupID'];
		}		
	}
	
//	public function setSnapUserID ($GroupID)   {$this->SnapUserID   = $GroupID;}
	public function setLongName   ($LongName)  {$this->LongName  = $LongName;}
	public function setShortName  ($ShortName) {$this->ShortName = $ShortName;}
	public function setPassword   ($Password)  {$this->Password  = $Password;}
	public function setEmail      ($Email)     {$this->Email     = $Email;}
	public function setGroupID    ($GroupID)   {$this->GroupID   = $GroupID;}
	
	public function save()
	{
		$database=$GLOBALS['DATABASE']->Recopy();
		
		if( $this->SnapUserID==0)  // create a new one
		{
			$sql = "INSERT INTO SnapUsers (LongName, ShortName, Password, email ) ";
			$sql .= "VALUES ";
			$sql .= "('$this->LongName', ";
			$sql .= "'$this->ShortName', ";
			$sql .= "'$this->Password', ";
			$sql .= "'$this->Email') ";
			print $sql;
			$database->executeSQL($sql);
			$newUserID = mysql_insert_id();
			$this->SnapUserID = $newUserID;

			$sql = "INSERT INTO SnapUserGroupMembers (SnapUserID, SnapUserGroupID) ";
			$sql .= "VALUES (".$this->SnapUserID.",".$this->GroupID.")";
			print $sql;
			$database->executeSQL($sql);
		
		}
		else // update existing
		{
			$sql = "UPDATE SnapUsers SET ";
			$sql .= "LongName  = '".$this->LongName."', ";
			$sql .= "ShortName = '".$this->ShortName."', ";
			$sql .= "Password  = '".$this->Password."', ";
			$sql .= "email     = '".$this->Email."' ";
			$sql .= "WHERE SnapUserID = ".$this->SnapUserID;
			print $sql;
			$database->executeSQL($sql);
			$newUserID = mysql_insert_id();
			$sql = "UPDATE SnapUserGroupMembers ";
			$sql .= "SET SnapUserGroupID = ".$this->GroupID;
			$sql .= " WHERE SnapUserID = ".$this->SnapUserID;
			print $sql;
			$database->executeSQL($sql);
		}
	}
	
}
